"""
Enhanced Data Extractor Module
Comprehensive data extraction for lines, buses, and transformers from DMF data
"""

import pandas as pd

from parser.dat_parser import Data_file
from parser.dmf_parser import parse_dmf_to_objects
from parser.inf_parser import INFParser


def extract_line_current_voltage_info(parsed_data):
    """
    从parse_dmf_to_objects()返回的数据中提取lines的电流相ID和对应bus的电压相ID。
    这是原有的extract_line_data函数的重命名版本，保持向后兼容性。

    Args:
        parsed_data (dict): parse_dmf_to_objects()函数返回的字典

    Returns:
        dict: 以line_name为key的字典，value为包含电流相ID和电压相ID的列表
        {
            'line_name_1': [
                [ia_idx, ib_idx, ic_idx, in_idx, ua_idx, ub_idx, uc_idx, un_idx],  # 电流相ID + 电压相ID
                # 如果line有多个ACC_Bran分支，会有多个列表
                ...
            ],
            'line_name_2': [...],
            ...
        }
    """
    return extract_line_data(parsed_data)


def extract_line_data(parsed_data):
    """
    从parse_dmf_to_objects()返回的数据中提取lines的电流相ID和对应bus的电压相ID。

    Args:
        parsed_data (dict): parse_dmf_to_objects()函数返回的字典

    Returns:
        dict: 以line_name为key的字典，value为包含电流相ID和电压相ID的列表
        {
            'line_name_1': [
                [ia_idx, ib_idx, ic_idx, in_idx, ua_idx, ub_idx, uc_idx, un_idx],  # 电流相ID + 电压相ID
                # 如果line有多个ACC_Bran分支，会有多个列表
                ...
            ],
            'line_name_2': [...],
            ...
        }
    """
    if not parsed_data or 'lines' not in parsed_data or 'buses' not in parsed_data:
        print("警告: 解析数据为空或缺少必要的字段")
        return {}

    # 创建bus_idx到bus对象的映射，便于快速查找
    bus_map = {bus.idx: bus for bus in parsed_data['buses']}

    result = {}

    for line in parsed_data['lines']:
        line_name = line.line_name
        result[line_name] = []

        # 获取对应的bus对象
        connected_bus = None
        if line.bus_ID is not None and line.bus_ID in bus_map:
            connected_bus = bus_map[line.bus_ID]
        else:
            # 如果没有找到对应Bus，尝试直接使用Line中的acv_chns
            if hasattr(line, "acv_chns") and line.acv_chns:
                connected_bus = type("PseudoBus", (), {"bus_name": f"{line_name}_pseudo", "acv_chns": line.acv_chns})()
                print(f"提示: Line {line_name} 没有关联Bus，使用其自身的acv_chns作为电压通道")
            else:
                print(f"警告: Line {line_name} 引用的Bus ID {line.bus_ID} 不存在，且未找到acv_chns")

        # 处理每个ACC_Bran分支
        for acc_bran in line.acc_brans:
            # 提取电流相ID和电压相ID
            combined_ids = extract_current_voltage_ids(acc_bran, connected_bus)
            result[line_name].append(combined_ids)

    return result


def extract_current_voltage_ids(acc_bran, connected_bus):
    """
    提取ACC_Bran的电流相ID和对应bus的电压相ID

    Args:
        acc_bran: ACC_Bran对象
        connected_bus: 连接的Bus对象

    Returns:
        list: 包含电流相ID和电压相ID的列表
              [ia_idx, ib_idx, ic_idx, in_idx, ua_idx, ub_idx, uc_idx, un_idx]
    """
    # 提取电流相ID
    current_ids = [
        acc_bran.ia_idx,  # A相电流
        acc_bran.ib_idx,  # B相电流
        acc_bran.ic_idx,  # C相电流
        acc_bran.in_idx   # N相电流
    ]

    # 提取对应bus的电压相ID
    voltage_ids = [None, None, None, None]  # 默认值
    if connected_bus and connected_bus.acv_chns:
        # 取第一个ACVChn的电压相ID（通常一个bus只有一个ACVChn）
        if len(connected_bus.acv_chns) > 0:
            acv_chn = connected_bus.acv_chns[0]
            voltage_ids = [
                acv_chn.ua_idx,  # A相电压
                acv_chn.ub_idx,  # B相电压
                acv_chn.uc_idx,  # C相电压
                acv_chn.un_idx   # N相电压
            ]

        # 如果bus有多个ACVChn，打印警告
        if len(connected_bus.acv_chns) > 1:
            print(f"警告: Bus {connected_bus.bus_name} 有多个ACVChn，只使用第一个")

    # 将电流相ID和电压相ID整合为一个list
    # 格式: [ia_idx, ib_idx, ic_idx, in_idx, ua_idx, ub_idx, uc_idx, un_idx]
    combined_ids = current_ids + voltage_ids
    return combined_ids


def extract_bus_data(dmf_data, dataframe=None):
    """
    提取母线数据

    Args:
        dmf_data (dict): DMF解析数据
        dataframe (pd.DataFrame, optional): 数据DataFrame，如果提供则会提取对应的时间序列数据

    Returns:
        dict: 母线数据字典
        {
            'bus_name': {
                'bus_idx': int,
                'channel_ids': [id1, id2, ...],
                'channel_info': {
                    'voltage_ids': [],
                    'current_ids': [],
                    'other_ids': []
                },
                'combined_data': pd.DataFrame (如果提供了dataframe),
                'bus_object': bus_object
            }
        }
    """
    bus_data = {}

    if 'buses' not in dmf_data or not dmf_data['buses']:
        print("  未找到母线信息")
        return bus_data

    print(f"  处理 {len(dmf_data['buses'])} 个母线...")

    for bus in dmf_data['buses']:
        bus_name = bus.bus_name
        bus_idx = bus.idx

        # 收集母线的所有通道ID
        all_channel_ids = []
        channel_info = {
            'voltage_ids': [],
            'current_ids': [],
            'other_ids': []
        }

        # 收集ACVChn（电压通道）
        for acv_chn in bus.acv_chns:
            voltage_ids = [acv_chn.ua_idx, acv_chn.ub_idx, acv_chn.uc_idx, acv_chn.un_idx]
            voltage_ids = [id for id in voltage_ids if id is not None]
            channel_info['voltage_ids'].extend(voltage_ids)
            all_channel_ids.extend(voltage_ids)

        # 收集AnaChn（模拟通道）
        for ana_chn in bus.ana_chns:
            if hasattr(ana_chn, 'idx_cfg') and ana_chn.idx_cfg is not None:
                channel_info['other_ids'].append(ana_chn.idx_cfg)
                all_channel_ids.append(ana_chn.idx_cfg)

        # 收集StaChn（状态通道）
        for sta_chn in bus.sta_chns:
            if hasattr(sta_chn, 'idx_cfg') and sta_chn.idx_cfg is not None:
                channel_info['other_ids'].append(sta_chn.idx_cfg)
                all_channel_ids.append(sta_chn.idx_cfg)

        if all_channel_ids:
            bus_data[bus_name] = {
                'bus_idx': bus_idx,
                'channel_ids': all_channel_ids,
                'channel_info': channel_info,
                'bus_object': bus
            }

            # 如果提供了dataframe，提取对应的时间序列数据
            if dataframe is not None:
                combined_data = extract_channels_by_ids(dataframe, all_channel_ids)
                bus_data[bus_name]['combined_data'] = combined_data

            print(f"    母线 {bus_name}: {len(all_channel_ids)} 个通道")
        else:
            print(f"    母线 {bus_name}: 无有效通道")

    return bus_data


def extract_transformer_data(dmf_data, dataframe=None):
    """
    提取变压器数据

    Args:
        dmf_data (dict): DMF解析数据
        dataframe (pd.DataFrame, optional): 数据DataFrame，如果提供则会提取对应的时间序列数据

    Returns:
        dict: 变压器数据字典
        {
            'transformer_name': {
                'trm_idx': int,
                'channel_ids': [id1, id2, ...],
                'winding_data': [
                    {
                        'location': str,
                        'voltage_ids': [],
                        'current_ids': [],
                        'other_ids': []
                    }
                ],
                'combined_data': pd.DataFrame (如果提供了dataframe),
                'transformer_object': transformer_object
            }
        }
    """
    transformer_data = {}

    if 'transformers' not in dmf_data or not dmf_data['transformers']:
        print("  未找到变压器信息")
        return transformer_data

    print(f"  处理 {len(dmf_data['transformers'])} 个变压器...")

    for transformer in dmf_data['transformers']:
        trm_name = transformer.trm_name
        trm_idx = transformer.idx

        # 收集变压器的所有通道ID
        all_channel_ids = []
        winding_data = []

        # 处理每个绕组
        for winding in transformer.windings:
            winding_info = {
                'location': winding.location,
                'voltage_ids': [],
                'current_ids': [],
                'other_ids': []
            }

            # 收集ACVChn（电压通道）
            for acv_chn in winding.acv_chns:
                voltage_ids = [acv_chn.ua_idx, acv_chn.ub_idx, acv_chn.uc_idx, acv_chn.un_idx]
                voltage_ids = [id for id in voltage_ids if id is not None]
                winding_info['voltage_ids'].extend(voltage_ids)
                all_channel_ids.extend(voltage_ids)

            # 收集ACC_Bran（电流通道）
            for acc_bran in winding.acc_brans:
                current_ids = [acc_bran.ia_idx, acc_bran.ib_idx, acc_bran.ic_idx, acc_bran.in_idx]
                current_ids = [id for id in current_ids if id is not None]
                winding_info['current_ids'].extend(current_ids)
                all_channel_ids.extend(current_ids)

            # 收集Igap
            for igap in winding.igaps:
                if igap.zgap_idx is not None:
                    winding_info['other_ids'].append(igap.zgap_idx)
                    all_channel_ids.append(igap.zgap_idx)
                if igap.zsgap_idx is not None:
                    winding_info['other_ids'].append(igap.zsgap_idx)
                    all_channel_ids.append(igap.zsgap_idx)

            winding_data.append(winding_info)

        # 收集变压器级别的通道
        # AnaChn
        for ana_chn in transformer.ana_chns:
            if hasattr(ana_chn, 'idx_cfg') and ana_chn.idx_cfg is not None:
                all_channel_ids.append(ana_chn.idx_cfg)

        # StaChn
        for sta_chn in transformer.sta_chns:
            if hasattr(sta_chn, 'idx_cfg') and sta_chn.idx_cfg is not None:
                all_channel_ids.append(sta_chn.idx_cfg)

        if all_channel_ids:
            transformer_data[trm_name] = {
                'trm_idx': trm_idx,
                'channel_ids': all_channel_ids,
                'winding_data': winding_data,
                'transformer_object': transformer
            }

            # 如果提供了dataframe，提取对应的时间序列数据
            if dataframe is not None:
                combined_data = extract_channels_by_ids(dataframe, all_channel_ids)
                transformer_data[trm_name]['combined_data'] = combined_data

            winding_count = len(winding_data)
            print(f"    变压器 {trm_name}: {len(all_channel_ids)} 个通道, {winding_count} 个绕组")
        else:
            print(f"    变压器 {trm_name}: 无有效通道")

    return transformer_data


def extract_channels_by_ids(dataframe, channel_ids):
    """
    根据通道ID列表从DataFrame中提取数据

    Args:
        dataframe (pd.DataFrame): 数据DataFrame
        channel_ids (list): 通道ID列表

    Returns:
        pd.DataFrame: 提取的数据
    """
    if not channel_ids:
        return pd.DataFrame()

    # 获取DataFrame的列（排除'Freq'列）
    data_columns = [col for col in dataframe.columns if col != 'Freq']

    # 根据ID映射到列名
    selected_columns = []
    for channel_id in channel_ids:
        if channel_id is not None:
            # ID = 列索引 + 1
            col_index = channel_id - 1
            if 0 <= col_index < len(data_columns):
                column_name = data_columns[col_index]
                selected_columns.append(column_name)

    if selected_columns:
        return dataframe[selected_columns].copy()
    else:
        return pd.DataFrame()


def extract_all_device_data(dmf_data, dataframe=None):
    """
    提取所有设备数据（线路、母线、变压器）

    Args:
        dmf_data (dict): DMF解析数据
        dataframe (pd.DataFrame, optional): 数据DataFrame

    Returns:
        dict: 包含所有设备数据的字典
        {
            'lines': dict,          # 线路数据
            'buses': dict,          # 母线数据
            'transformers': dict    # 变压器数据
        }
    """
    print("\n" + "=" * 60)
    print("提取所有设备数据")
    print("=" * 60)

    # 提取线路数据
    print("1. 提取线路数据...")
    line_data = extract_line_current_voltage_info(dmf_data)

    # 如果提供了dataframe，提取线路的时间序列数据
    extracted_line_data = {}
    if dataframe is not None:
        extracted_line_data = extract_data_by_channel_mapping(line_data, dataframe)

    # 提取母线数据
    print("\n2. 提取母线数据...")
    bus_data = extract_bus_data(dmf_data, dataframe)

    # 提取变压器数据
    print("\n3. 提取变压器数据...")
    transformer_data = extract_transformer_data(dmf_data, dataframe)

    # 统计信息
    total_line_branches = sum(
        len(branches) for branches in extracted_line_data.values()) if extracted_line_data else len(line_data)
    total_buses = len(bus_data)
    total_transformers = len(transformer_data)

    print(f"\n提取完成:")
    print(f"  线路: {len(line_data)} 条，共 {total_line_branches} 个分支")
    print(f"  母线: {total_buses} 个")
    print(f"  变压器: {total_transformers} 个")

    return {
        'lines': extracted_line_data if extracted_line_data else line_data,
        'buses': bus_data,
        'transformers': transformer_data,
        'raw_line_data': line_data  # 保留原始线路数据供参考
    }


# 保持向后兼容性的函数别名
def print_line_current_voltage_summary(line_data):
    """
    打印line电流相和电压相信息的摘要

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果
    """
    print("=" * 80)
    print("Line电流相与电压相ID信息摘要")
    print("=" * 80)

    for line_name, id_lists in line_data.items():
        print(f"\nLine: {line_name}")
        print(f"分支数量: {len(id_lists)}")

        for i, combined_ids in enumerate(id_lists, 1):
            print(f"  分支 {i}:")
            # 前4个是电流相ID，后4个是电压相ID
            current_ids = combined_ids[:4]
            voltage_ids = combined_ids[4:8] if len(combined_ids) >= 8 else [None, None, None, None]

            print(f"    电流相ID: [IA={current_ids[0]}, IB={current_ids[1]}, IC={current_ids[2]}, IN={current_ids[3]}]")
            print(f"    电压相ID: [UA={voltage_ids[0]}, UB={voltage_ids[1]}, UC={voltage_ids[2]}, UN={voltage_ids[3]}]")
            print(f"    整合列表: {combined_ids}")


def get_line_phase_ids(line_data, line_name):
    """
    根据line_name获取该line的电流相和电压相ID

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果
        line_name (str): 要查询的line名称

    Returns:
        list: 该line的相ID信息列表，如果line不存在则返回None
    """
    return line_data.get(line_name, None)


def get_all_current_ids(line_data):
    """
    获取所有line的电流相ID（扁平化列表）

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果

    Returns:
        list: 所有电流相ID的扁平化列表
    """
    all_current_ids = []
    for line_name, id_lists in line_data.items():
        for combined_ids in id_lists:
            # 前4个是电流相ID
            current_ids = combined_ids[:4]
            # 过滤掉None值
            valid_current_ids = [id for id in current_ids if id is not None]
            all_current_ids.extend(valid_current_ids)

    return all_current_ids


def get_all_voltage_ids(line_data):
    """
    获取所有对应bus的电压相ID（扁平化列表）

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果

    Returns:
        list: 所有电压相ID的扁平化列表
    """
    all_voltage_ids = []
    for line_name, id_lists in line_data.items():
        for combined_ids in id_lists:
            # 后4个是电压相ID
            voltage_ids = combined_ids[4:8] if len(combined_ids) >= 8 else []
            # 过滤掉None值
            valid_voltage_ids = [id for id in voltage_ids if id is not None]
            all_voltage_ids.extend(valid_voltage_ids)

    return list(set(all_voltage_ids))  # 去重，因为多个line可能连接同一个bus


def extract_data_by_channel_names(line_data, dataframe):
    """
    根据line_data中的通道ID从时间序列DataFrame中提取对应的数据

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果
                         格式: {'line_name': [[ia, ib, ic, in, ua, ub, uc, un], ...]}
        dataframe (pd.DataFrame): 从export_data()方法获取的DataFrame
                                 - 索引: 时间戳
                                 - 列: 通道名称(cch_id)
                                 - 包含'Freq'列

    Returns:
        dict: 以line_name为key的字典，包含每个line的时间序列数据
        {
            'line_name_1': [
                {
                    'current_data': pd.DataFrame,     # 电流相时间序列数据 (时间 x 4列)
                    'voltage_data': pd.DataFrame,     # 电压相时间序列数据 (时间 x 4列)
                    'combined_data': pd.DataFrame,    # 合并时间序列数据 (时间 x 8列)
                    'ids': [ia, ib, ic, in, ua, ub, uc, un],  # 对应的通道ID
                    'channel_names': [ia_name, ib_name, ic_name, in_name, ua_name, ub_name, uc_name, un_name]
                },
                ...  # 如果有多个分支
            ],
            ...
        }
    """

    # 获取除'Freq'之外的所有通道列
    available_channels = [col for col in dataframe.columns if col != 'Freq']

    result = {}

    for line_name, id_lists in line_data.items():
        result[line_name] = []

        for branch_ids in id_lists:
            # 分离电流和电压ID
            current_ids = branch_ids[:4]  # [IA, IB, IC, IN]
            voltage_ids = branch_ids[4:8] if len(branch_ids) >= 8 else [None, None, None, None]

            # 查找对应的通道名称（这里需要配置对象来映射ID到通道名）
            # 由于没有cfg对象，我们假设DataFrame的列名就是通道名或ID的字符串表示

            # 提取电流数据
            current_columns = []
            current_names = []
            for i, current_id in enumerate(current_ids):
                if current_id is not None:
                    # 尝试多种方式匹配列名
                    matching_col = None
                    for col in available_channels:
                        if (str(current_id) in col or
                                col.endswith(f"_{current_id}") or
                                col.startswith(f"{current_id}_")):
                            matching_col = col
                            break

                    if matching_col:
                        current_columns.append(matching_col)
                        current_names.append(matching_col)
                    else:
                        print(f"警告: 未找到电流通道ID {current_id} 对应的列")
                        current_names.append(f"IA_missing")
                        if i == 0:
                            current_names[-1] = "IA_missing"
                        elif i == 1:
                            current_names[-1] = "IB_missing"
                        elif i == 2:
                            current_names[-1] = "IC_missing"
                        elif i == 3:
                            current_names[-1] = "IN_missing"
                else:
                    current_names.append(None)

            # 提取电压数据
            voltage_columns = []
            voltage_names = []
            for i, voltage_id in enumerate(voltage_ids):
                if voltage_id is not None:
                    # 尝试多种方式匹配列名
                    matching_col = None
                    for col in available_channels:
                        if (str(voltage_id) in col or
                                col.endswith(f"_{voltage_id}") or
                                col.startswith(f"{voltage_id}_")):
                            matching_col = col
                            break

                    if matching_col:
                        voltage_columns.append(matching_col)
                        voltage_names.append(matching_col)
                    else:
                        print(f"警告: 未找到电压通道ID {voltage_id} 对应的列")
                        if i == 0:
                            voltage_names.append("UA_missing")
                        elif i == 1:
                            voltage_names.append("UB_missing")
                        elif i == 2:
                            voltage_names.append("UC_missing")
                        elif i == 3:
                            voltage_names.append("UN_missing")
                else:
                    voltage_names.append(None)

            # 创建数据子集
            current_data = dataframe[current_columns].copy() if current_columns else pd.DataFrame(index=dataframe.index)
            voltage_data = dataframe[voltage_columns].copy() if voltage_columns else pd.DataFrame(index=dataframe.index)

            # 合并数据
            all_columns = current_columns + voltage_columns
            combined_data = dataframe[all_columns].copy() if all_columns else pd.DataFrame(index=dataframe.index)

            # 重命名列以便于识别
            if not current_data.empty:
                phase_labels = ['IA', 'IB', 'IC', 'IN']
                rename_dict = {col: f"{phase_labels[i]}_{col}" for i, col in enumerate(current_columns)}
                current_data = current_data.rename(columns=rename_dict)

            if not voltage_data.empty:
                phase_labels = ['UA', 'UB', 'UC', 'UN']
                rename_dict = {col: f"{phase_labels[i]}_{col}" for i, col in enumerate(voltage_columns)}
                voltage_data = voltage_data.rename(columns=rename_dict)

            branch_data = {
                'current_data': current_data,
                'voltage_data': voltage_data,
                'combined_data': combined_data,
                'ids': branch_ids,
                'channel_names': current_names + voltage_names,
                'available_current_channels': current_columns,
                'available_voltage_channels': voltage_columns
            }

            result[line_name].append(branch_data)

    return result


def extract_data_by_channel_mapping(line_data, dataframe):
    """
    使用通道映射表从DataFrame中提取数据
    line_data中的id与dataframe的对应关系: id = dataframe_column_index + 1

    Args:
        line_data (dict): extract_line_current_voltage_info()函数返回的结果
        dataframe (pd.DataFrame): 从export_data()方法获取的DataFrame
        channel_mapping (dict, optional): 通道映射表 {channel_id: channel_name}

    Returns:
        dict: 提取的数据结果
    """
    result = {}

    # 获取DataFrame的列（排除'Freq'列）
    data_columns = [col for col in dataframe.columns if col != 'Freq']

    for line_name, id_lists in line_data.items():
        result[line_name] = []

        for branch_index, branch_ids in enumerate(id_lists):
            print(f"\n处理 {line_name} 分支{branch_index}: {branch_ids}")

            # 分离电流和电压ID
            current_ids = branch_ids[:4]
            voltage_ids = branch_ids[4:8] if len(branch_ids) >= 8 else [None, None, None, None]

            # 根据ID获取对应的列名（ID = 列索引 + 1）
            current_columns = []
            voltage_columns = []
            current_names = []
            voltage_names = []

            # 处理电流ID
            for i, current_id in enumerate(current_ids):
                phase_name = ['IA', 'IB', 'IC', 'IN'][i]
                if current_id is not None:
                    # 将ID转换为DataFrame列索引（ID从1开始，索引从0开始）
                    col_index = current_id - 1

                    if 0 <= col_index < len(data_columns):
                        column_name = data_columns[col_index]
                        current_columns.append(column_name)
                        current_names.append(column_name)
                    else:
                        print(f"    警告: {phase_name} ID{current_id} 超出范围 (1-{len(data_columns)})")
                        current_names.append(f"{phase_name}_missing")
                else:
                    current_names.append(None)
                    print(f"    {phase_name}: None")

            # 处理电压ID
            for i, voltage_id in enumerate(voltage_ids):
                phase_name = ['UA', 'UB', 'UC', 'UN'][i]
                if voltage_id is not None:
                    # 将ID转换为DataFrame列索引
                    col_index = voltage_id - 1

                    if 0 <= col_index < len(data_columns):
                        column_name = data_columns[col_index]
                        voltage_columns.append(column_name)
                        voltage_names.append(column_name)
                    else:
                        print(f"    警告: {phase_name} ID{voltage_id} 超出范围 (1-{len(data_columns)})")
                        voltage_names.append(f"{phase_name}_missing")
                else:
                    voltage_names.append(None)
                    print(f"    {phase_name}: None")

            # 提取数据
            current_data = dataframe[current_columns].copy() if current_columns else pd.DataFrame(index=dataframe.index)
            voltage_data = dataframe[voltage_columns].copy() if voltage_columns else pd.DataFrame(index=dataframe.index)
            combined_data = dataframe[current_columns + voltage_columns].copy() if (
                    current_columns + voltage_columns) else pd.DataFrame(index=dataframe.index)

            # 重命名列以便于识别相位
            if not current_data.empty:
                phase_labels = ['IA', 'IB', 'IC', 'IN']
                rename_dict = {}
                for i, col in enumerate(current_columns):
                    if i < len(phase_labels):
                        rename_dict[col] = f"{phase_labels[i]}_{col}"
                current_data = current_data.rename(columns=rename_dict)

            if not voltage_data.empty:
                phase_labels = ['UA', 'UB', 'UC', 'UN']
                rename_dict = {}
                for i, col in enumerate(voltage_columns):
                    if i < len(phase_labels):
                        rename_dict[col] = f"{phase_labels[i]}_{col}"
                voltage_data = voltage_data.rename(columns=rename_dict)

            branch_data = {
                'current_data': current_data,
                'voltage_data': voltage_data,
                'combined_data': combined_data,
                'ids': branch_ids,
                'channel_names': current_names + voltage_names,
                'available_current_channels': current_columns,
                'available_voltage_channels': voltage_columns,
                'id_to_column_mapping': {
                    **{current_ids[i]: current_columns[i] for i in range(len(current_columns)) if
                       current_ids[i] is not None},
                    **{voltage_ids[i]: voltage_columns[i] for i in range(len(voltage_columns)) if
                       voltage_ids[i] is not None}
                }
            }

            result[line_name].append(branch_data)

    return result


def convert_inf_to_dmf_format(inf_parser: INFParser) -> dict:
    """
    将INF解析器的数据转换为DMF兼容格式
    优化后的版本，完善了数据结构和错误处理

    Args:
        inf_parser (INFParser): 已解析的INF文件数据

    Returns:
        dict: DMF兼容格式的数据
    """
    
    # 创建一个模拟的DMF数据结构
    dmf_data = {
        'lines': [],
        'buses': [],
        'transformers': [],
    }

    # 转换线路数据
    lines_data = inf_parser.get_lines_data()
    
    for i, line_data in enumerate(lines_data):
        try:
            # 创建一个模拟的线路对象
            line_obj = type('Line', (), {
                'line_name': line_data.get('dev_name', f'Line_{i+1}'),
                'idx': int(line_data.get('dev_id', i+1)) if line_data.get('dev_id') else i+1,
                'bus_ID': line_data.get('bus_id', None),  # 使用INF中的bus_id字段
                'acc_brans': [],
                'acv_chns': [],
            })()

            # 添加电流通道作为ACC_Bran模拟对象
            current_channels = line_data.get('current_channels', [])
            voltage_channels = line_data.get('voltage_channels', [])
            
            if current_channels:
                acc_bran = type('ACC_Bran', (), {
                    'ia_idx': current_channels[0] if len(current_channels) > 0 else None,
                    'ib_idx': current_channels[1] if len(current_channels) > 1 else None,
                    'ic_idx': current_channels[2] if len(current_channels) > 2 else None,
                    'in_idx': current_channels[3] if len(current_channels) > 3 else None,
                })()
                line_obj.acc_brans.append(acc_bran)

                # 添加电压通道作为ACVChn模拟对象
            if voltage_channels:
                acv_chn = type('ACVChn', (), {
                    'ua_idx': voltage_channels[0] if len(voltage_channels) > 0 else None,
                    'ub_idx': voltage_channels[1] if len(voltage_channels) > 1 else None,
                    'uc_idx': voltage_channels[2] if len(voltage_channels) > 2 else None,
                    'un_idx': voltage_channels[3] if len(voltage_channels) > 3 else None,
                })()
                line_obj.acv_chns.append(acv_chn)

            dmf_data['lines'].append(line_obj)
            
        except Exception as e:
            print(f"    警告: 转换线路数据 {i+1} 时出错: {e}")
            continue

    # 转换母线数据
    buses_data = inf_parser.get_buses_data()
    
    for i, bus_data in enumerate(buses_data):
        try:
            # 创建一个模拟的母线对象
            bus_obj = type('Bus', (), {
                'bus_name': bus_data.get('dev_name', f'Bus_{i+1}'),
                'idx': int(bus_data.get('dev_id', i+1)) if bus_data.get('dev_id') else i+1,
                'acv_chns': [],
                'ana_chns': [],
                'sta_chns': [],
            })()

            # 添加电压通道作为ACVChn模拟对象
            voltage_channels = bus_data.get('voltage_channels', [])
            if voltage_channels:
                acv_chn = type('ACVChn', (), {
                    'ua_idx': voltage_channels[0] if len(voltage_channels) > 0 else None,
                    'ub_idx': voltage_channels[1] if len(voltage_channels) > 1 else None,
                    'uc_idx': voltage_channels[2] if len(voltage_channels) > 2 else None,
                    'un_idx': voltage_channels[3] if len(voltage_channels) > 3 else None,
                })()
                bus_obj.acv_chns.append(acv_chn)

            # 添加状态通道
            status_channels = bus_data.get('status_channels', [])
            for status_ch in status_channels:
                if status_ch:
                    sta_chn = type('StaChn', (), {
                        'idx_cfg': status_ch
                    })()
                    bus_obj.sta_chns.append(sta_chn)


            dmf_data['buses'].append(bus_obj)
            
        except Exception as e:
            print(f"    警告: 转换母线数据 {i+1} 时出错: {e}")
            continue

    # 转换变压器数据
    transformers_data = inf_parser.get_transformers_data()
    
    for i, tr_data in enumerate(transformers_data):
        try:
            # 创建一个模拟的变压器对象
            transformer_obj = type('Transformer', (), {
                'trm_name': tr_data.get('dev_name', f'Transformer_{i+1}'),
                'idx': int(tr_data.get('dev_id', i+1)) if tr_data.get('dev_id') else i+1,
                'windings': [],
                'ana_chns': [],
                'sta_chns': [],
            })()

            # 根据INF数据中的绕组信息创建绕组
            windings_info = []
            
            # 高压侧绕组
            hv_voltage = tr_data.get('voltage_hv_channels', [])
            hv_current = tr_data.get('current_hv_channels', [])
            if hv_voltage or hv_current:
                windings_info.append({
                    'location': 'HV',
                    'voltage_channels': hv_voltage,
                    'current_channels': hv_current
                })
            
            # 中压侧绕组
            mv_voltage = tr_data.get('voltage_mv_channels', [])
            mv_current = tr_data.get('current_mv_channels', [])
            if mv_voltage or mv_current:
                windings_info.append({
                    'location': 'MV', 
                    'voltage_channels': mv_voltage,
                    'current_channels': mv_current
                })
            
            # 低压侧绕组
            lv_voltage = tr_data.get('voltage_lv_channels', [])
            lv_current = tr_data.get('current_lv_channels', [])
            if lv_voltage or lv_current:
                windings_info.append({
                    'location': 'LV',
                    'voltage_channels': lv_voltage, 
                    'current_channels': lv_current
                })

            # 如果没有找到绕组信息，创建一个默认绕组
            if not windings_info:
                windings_info.append({
                    'location': 'HV',
                    'voltage_channels': [],
                    'current_channels': []
                })

            # 创建绕组对象
            for winding_info in windings_info:
                winding_obj = type('Winding', (), {
                    'location': winding_info['location'],
                    'acv_chns': [],
                    'acc_brans': [],
                    'igaps': [],
                })()

                # 添加电压通道
                voltage_channels = winding_info['voltage_channels']
                if voltage_channels:
                    acv_chn = type('ACVChn', (), {
                        'ua_idx': voltage_channels[0] if len(voltage_channels) > 0 else None,
                        'ub_idx': voltage_channels[1] if len(voltage_channels) > 1 else None,
                        'uc_idx': voltage_channels[2] if len(voltage_channels) > 2 else None,
                        'un_idx': voltage_channels[3] if len(voltage_channels) > 3 else None,
                    })()
                    winding_obj.acv_chns.append(acv_chn)

                # 添加电流通道
                current_channels = winding_info['current_channels']
                if current_channels:
                    acc_bran = type('ACC_Bran', (), {
                        'ia_idx': current_channels[0] if len(current_channels) > 0 else None,
                        'ib_idx': current_channels[1] if len(current_channels) > 1 else None,
                        'ic_idx': current_channels[2] if len(current_channels) > 2 else None,
                        'in_idx': current_channels[3] if len(current_channels) > 3 else None,
                    })()
                    winding_obj.acc_brans.append(acc_bran)

                transformer_obj.windings.append(winding_obj)

            # 添加其他通道
            oth_achns = tr_data.get('oth_achns', [])
            for oth_ch in oth_achns:
                if oth_ch:
                    ana_chn = type('AnaChn', (), {
                        'idx_cfg': oth_ch
                    })()
                    transformer_obj.ana_chns.append(ana_chn)

            oth_status_channels = tr_data.get('oth_status_channels', [])
            for status_ch in oth_status_channels:
                if status_ch:
                    sta_chn = type('StaChn', (), {
                        'idx_cfg': status_ch
                    })()
                    transformer_obj.sta_chns.append(sta_chn)

            dmf_data['transformers'].append(transformer_obj)
            
        except Exception as e:
            print(f"    警告: 转换变压器数据 {i+1} 时出错: {e}")
            continue

    print(f"✓ INF转DMF完成: {len(dmf_data['lines'])}条线路, {len(dmf_data['buses'])}个母线, {len(dmf_data['transformers'])}个变压器")
    return dmf_data



def create_channel_mapping_from_cfg(cfg_obj):
    """
    从cfg对象创建通道映射表

    Args:
        cfg_obj: CFG配置对象

    Returns:
        dict: {channel_id: channel_name}的映射表
    """
    mapping = {}

    # 添加模拟通道
    for ch in cfg_obj.Achannel_info:
        mapping[ch.mno] = ch.cch_id

    # 添加数字通道
    for ch in cfg_obj.Dchannel_info:
        mapping[ch.mno] = ch.cch_id

    return mapping


def print_extraction_summary(extracted_data):
    """
    打印提取数据的摘要信息

    Args:
        extracted_data (dict): extract_data_by_channel_names()或extract_data_by_channel_mapping()的返回结果
    """
    print("=" * 80)
    print("数据提取摘要")
    print("=" * 80)

    for line_name, branches in extracted_data.items():
        print(f"\nLine: {line_name}")
        print(f"分支数量: {len(branches)}")

        for i, branch in enumerate(branches, 1):
            print(f"  分支 {i}:")
            print(f"    通道ID: {branch['ids']}")
            print(f"    电流数据形状: {branch['current_data'].shape}")
            print(f"    电压数据形状: {branch['voltage_data'].shape}")
            print(f"    合并数据形状: {branch['combined_data'].shape}")

            if 'available_current_channels' in branch:
                print(f"    可用电流通道: {branch['available_current_channels']}")
                print(f"    可用电压通道: {branch['available_voltage_channels']}")


def print_all_device_summary(all_device_data):
    """
    打印所有设备数据的摘要信息

    Args:
        all_device_data (dict): extract_all_device_data()的返回结果
    """
    print("=" * 80)
    print("所有设备数据摘要")
    print("=" * 80)

    # 线路摘要
    lines = all_device_data.get('lines', {})
    print(f"\n线路数据: {len(lines)} 条线路")
    for line_name, branches in lines.items():
        if isinstance(branches, list):
            print(f"  {line_name}: {len(branches)} 个分支")
        else:
            print(f"  {line_name}: 基础数据")

    # 母线摘要
    buses = all_device_data.get('buses', {})
    print(f"\n母线数据: {len(buses)} 个母线")
    for bus_name, bus_data in buses.items():
        channel_count = len(bus_data.get('channel_ids', []))
        print(f"  {bus_name}: {channel_count} 个通道")

    # 变压器摘要
    transformers = all_device_data.get('transformers', {})
    print(f"\n变压器数据: {len(transformers)} 个变压器")
    for trm_name, trm_data in transformers.items():
        channel_count = len(trm_data.get('channel_ids', []))
        winding_count = len(trm_data.get('winding_data', []))
        print(f"  {trm_name}: {channel_count} 个通道, {winding_count} 个绕组")


def get_statistics_for_line(extracted_data, line_name, branch_index=0):
    """
    计算特定line和分支的统计信息

    Args:
        extracted_data (dict): 提取的数据
        line_name (str): line名称
        branch_index (int): 分支索引，默认为0

    Returns:
        dict: 统计信息
    """
    if line_name not in extracted_data:
        print(f"Line {line_name} 不存在")
        return None

    if branch_index >= len(extracted_data[line_name]):
        print(f"分支索引 {branch_index} 超出范围")
        return None

    branch_data = extracted_data[line_name][branch_index]

    stats = {
        'line_name': line_name,
        'branch_index': branch_index,
        'ids': branch_data['ids'],
        'time_range': (branch_data['combined_data'].index.min(), branch_data['combined_data'].index.max()),
        'data_points': len(branch_data['combined_data']),
        'current_stats': {},
        'voltage_stats': {}
    }

    # 电流统计
    if not branch_data['current_data'].empty:
        stats['current_stats'] = {
            'mean': branch_data['current_data'].mean().to_dict(),
            'std': branch_data['current_data'].std().to_dict(),
            'min': branch_data['current_data'].min().to_dict(),
            'max': branch_data['current_data'].max().to_dict()
        }

    # 电压统计
    if not branch_data['voltage_data'].empty:
        stats['voltage_stats'] = {
            'mean': branch_data['voltage_data'].mean().to_dict(),
            'std': branch_data['voltage_data'].std().to_dict(),
            'min': branch_data['voltage_data'].min().to_dict(),
            'max': branch_data['voltage_data'].max().to_dict()
        }

    return stats


def get_statistics_for_bus(bus_data, bus_name):
    """
    计算特定母线的统计信息

    Args:
        bus_data (dict): 母线数据
        bus_name (str): 母线名称

    Returns:
        dict: 统计信息
    """
    if bus_name not in bus_data:
        print(f"母线 {bus_name} 不存在")
        return None

    bus_info = bus_data[bus_name]

    stats = {
        'bus_name': bus_name,
        'bus_idx': bus_info['bus_idx'],
        'channel_ids': bus_info['channel_ids'],
        'channel_count': len(bus_info['channel_ids']),
        'channel_info': bus_info['channel_info']
    }

    # 如果有时间序列数据，计算统计信息
    if 'combined_data' in bus_info and not bus_info['combined_data'].empty:
        combined_data = bus_info['combined_data']
        stats.update({
            'time_range': (combined_data.index.min(), combined_data.index.max()),
            'data_points': len(combined_data),
            'data_stats': {
                'mean': combined_data.mean().to_dict(),
                'std': combined_data.std().to_dict(),
                'min': combined_data.min().to_dict(),
                'max': combined_data.max().to_dict()
            }
        })

    return stats


def get_statistics_for_transformer(transformer_data, transformer_name):
    """
    计算特定变压器的统计信息

    Args:
        transformer_data (dict): 变压器数据
        transformer_name (str): 变压器名称

    Returns:
        dict: 统计信息
    """
    if transformer_name not in transformer_data:
        print(f"变压器 {transformer_name} 不存在")
        return None

    trm_info = transformer_data[transformer_name]

    stats = {
        'transformer_name': transformer_name,
        'trm_idx': trm_info['trm_idx'],
        'channel_ids': trm_info['channel_ids'],
        'channel_count': len(trm_info['channel_ids']),
        'winding_data': trm_info['winding_data'],
        'winding_count': len(trm_info['winding_data'])
    }

    # 如果有时间序列数据，计算统计信息
    if 'combined_data' in trm_info and not trm_info['combined_data'].empty:
        combined_data = trm_info['combined_data']
        stats.update({
            'time_range': (combined_data.index.min(), combined_data.index.max()),
            'data_points': len(combined_data),
            'data_stats': {
                'mean': combined_data.mean().to_dict(),
                'std': combined_data.std().to_dict(),
                'min': combined_data.min().to_dict(),
                'max': combined_data.max().to_dict()
            }
        })

    return stats


def extract_device_data_comprehensive(file_name: str, data_dir: str = 'data'):
    """
    综合数据提取函数，一次性完成所有步骤

    Args:
        file_name (str): 文件名（不含扩展名）
        data_dir (str): 数据目录

    Returns:
        dict: 包含所有提取数据的综合结果
        {
            'cfg_obj': CFG对象,
            'dmf_data': DMF解析数据,
            'dataframe': 时间序列DataFrame,
            'all_device_data': 所有设备数据,
            'success': bool,
            'error': str (如果失败)
        }
    """
    try:
        print(f"开始综合数据提取: {file_name}")

        # 文件路径
        dmf_file = f'{data_dir}/{file_name}.DMF'
        cfg_file = f'{data_dir}/{file_name}.cfg'
        inf_file = f'{data_dir}/{file_name}.inf'

        print("1. 解析配置文件...")
        # 解析CFG文件
        from parser.cfg_parser import CfgParser
        cfg_obj = CfgParser(cfg_file)
        if not cfg_obj.parse():
            raise ValueError(f"CFG文件解析失败: {cfg_file}")

        print("2. 解析DMF文件...")
        # 解析DMF文件
        dmf_data = parse_dmf_to_objects(dmf_file)
        if not dmf_data:
            # 如果DMF文件不存在或解析失败，尝试解析INF文件
            print("DMF文件不存在或解析失败，尝试解析INF文件...")
            inf_parser = INFParser()
            if inf_parser.parse_file(inf_file):
                print("INF文件解析成功，正在转换为DMF兼容格式...")
                # 将INF数据转换为DMF兼容格式
                dmf_data = convert_inf_to_dmf_format(inf_parser)
            else:
                raise ValueError(f"DMF文件解析失败: {dmf_file}，且INF文件解析也失败: {inf_file}")

        print("3. 处理数据文件...")

        # 创建数据文件对象
        data_file = Data_file(cfg_obj)
        if not data_file.check_file():
            raise ValueError("数据文件不存在或校验失败")

        # 解析数据
        data_file.parse_data(use_optimized=True)
        data_file.get_channels_data()

        # 导出为DataFrame
        dataframe = data_file.export_data()

        print("4. 提取所有设备数据...")
        # 提取所有设备数据
        all_device_data = extract_all_device_data(dmf_data, dataframe)

        return {
            'cfg_obj': cfg_obj,
            'dmf_data': dmf_data,
            'dataframe': dataframe,
            'all_device_data': all_device_data,
            'success': True
        }

    except Exception as e:
        print(f"数据提取失败: {e}")
        import traceback
        traceback.print_exc()

        return {
            'cfg_obj': None,
            'dmf_data': None,
            'dataframe': None,
            'all_device_data': None,
            'zero_sequence_channels': [],
            'success': False,
            'error': str(e)
        }


# 使用示例
if __name__ == "__main__":
    # 示例1: 基本使用流程（保持向后兼容）

    # # 1. 解析DMF文件并提取line信息
    # parsed_data = parse_dmf_to_objects("data/SH11200_RCD_5460_20241029_080322_428_S.dmf")
    # line_data = extract_line_current_voltage_info(parsed_data)
    #
    # # 2. 解析CFG和DAT文件获取DataFrame
    # cfg = Cfg_file("data/SH11200_RCD_5460_20241029_080322_428_S.cfg")
    # cfg.parse()
    # dat = Data_file(cfg)
    # if dat.check_file():
    #     dat.parse_data(use_optimized=True)
    #     dat.get_channels_data()
    #
    # df = dat.export_data()
    #
    # # 3. 根据通道ID提取对应数据
    # extracted_data = extract_data_by_channel_mapping(line_data, df)
    # print_extraction_summary(extracted_data)
    #
    # # 示例2: 提取所有设备数据（新功能）
    # print("\n" + "=" * 60)
    # print("提取所有设备数据示例")
    # print("=" * 60)
    #
    # all_device_data = extract_all_device_data(parsed_data, df)
    # print_all_device_summary(all_device_data)

    # 示例3: 一步完成所有提取（最简单）
    print("\n" + "=" * 60)
    print("综合提取示例")
    print("=" * 60)

    file_name = 'SH11455_RCD_2175_20240929_160740_159_F'  # 不含扩展名
    result = extract_device_data_comprehensive(file_name)

